package com.md.api.annotation;

import com.md.api.common.utils.RedisUtil;
import com.md.api.entity.HttpResult;
import com.md.api.common.utils.StringUtils;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


/**
 * @Author Minco
 * @Date 16:02 2020-08-13
 * @Description aop解析注解
 */
@Slf4j
@Aspect
@Component
public class NoRepeatSubmitAop {

    @Autowired
    RedisUtil redisUtil;

    @Pointcut("@annotation(com.md.api.annotation.NoRepeatSubmit)")
    public void logPointCut() {

    }

    @Synchronized
    @Around("logPointCut()")
    public Object arround(ProceedingJoinPoint pjp) throws Throwable {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            Object o = pjp.proceed();
            return o;
        }
        String key = token + "-" + request.getServletPath();
        if ( !redisUtil.hasKey(key) ) {// 如果缓存中有这个url视为重复提交
            Object o = pjp.proceed();
            redisUtil.set(key, key,1, TimeUnit.SECONDS);
            return o;
        } else {
            //点了同样的URL继续限制，直到2次点击中间间隔超过了限制
//            redisUtil.expire(key, 2);
            return HttpResult.REQUEST_NOT_SUPPORTED;
        }

    }

}